<template>
  <div id="expand-table-layout" class="expand-table-layout">
    <div class="filter-container">
      <el-button v-waves type="primary" size="mini" icon="el-icon-plus" @click="handleCreate">Add</el-button>
    </div>

    <!-- table -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="loading"
      element-loading-text="请给我点时间！"
      :data="list"
      fit
      border
      row-key="sid"
      style="width: 100%"
      row-class-name="row-no-expand"
      :expand-row-keys="expandRowKeys"
    >
      <!-- @expand-change="onExpandChange" -->
      <el-table-column align="center" type="expand">
        <template slot-scope="{row}">
          <SubTableItem :data="row" @update="onUpdateList" />
        </template>
      </el-table-column>
      <el-table-column label align="center" width="50">
        <template slot-scope="{row, $index}">
          <el-link
            type="info"
            :underline="false"
            v-if="row.items"
            @click="openDialogTable($index, row.sid)"
          >
            <i
              :class="expandRowKeys.includes(row.sid) ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"
            />
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="Index" type="index" width="65" align="center" />
      <el-table-column label="Type" prop="type" min-width="120" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Text" prop="text" min-width="120" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.text">{{ row.text }}</span>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Mode" prop="mode" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.mode">{{ row.mode }}</el-tag>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Style" prop="style" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.style">{{ row.style }}</el-tag>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Pict" prop="pict" align="center">
        <template slot-scope="{row}">
          <el-image
            v-if="row.pict"
            style="width: 50px; height: 50px"
            :src="row.pict"
            fit="contain"
            :preview-src-list="[row.pict]"
          />
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Click" prop="click" min-width="100" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.click" style="color:#1890ff;white-space: nowrap;">
            <a :href="row.click">{{ row.click }}</a>
          </span>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column
        label="Actions"
        align="center"
        min-width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row,$index}">
          <el-button
            v-waves
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          >Edit</el-button>
          <el-button
            v-waves
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(row, $index)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="Type" prop="type">
          <el-select
            v-model="temp.type"
            :disabled="dialogStatus === 'edit'"
            class="filter-item"
            placeholder="Please select"
            @change="onChangeType"
          >
            <el-option v-for="item in types" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <template v-if="temp.type">
          <el-form-item v-if="temp.type === 'title'" label="Title" prop="text">
            <el-input v-model="temp.text" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'description'" label="Description" prop="text">
            <el-input v-model="temp.text" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
          </el-form-item>
          <template v-if="temp.type === 'one_big_picture'">
            <el-form-item label="Pict" prop="pict">
              <image-upload />
            </el-form-item>
            <el-form-item label="Click" prop="click">
              <el-input v-model="temp.click">
                <template slot="prepend">
                  <div class="pic-prepend">
                    <el-select
                      v-model="temp.clickPrepend"
                      class="filter-item"
                      placeholder="Please select"
                    >
                      <el-option v-for="item in clickTypes" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-input>
            </el-form-item>
          </template>
          <template v-if="['list_of_clicks', 'list_of_products'].includes(temp.type)">
            <el-form-item label="Mode" prop="mode">
              <el-radio-group v-model="temp.mode">
                <el-radio-button label="wrap" />
                <el-radio-button label="unwrap" />
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="!(temp.type === 'list_of_products')" label="Style" prop="style">
              <el-radio-group v-model="temp.style" :disabled="dialogStatus === 'edit'">
                <el-radio-button label="link" />
                <el-radio-button label="button" />
                <el-radio-button label="picture" />
              </el-radio-group>
            </el-form-item>
            <template
              v-if="!(dialogStatus === 'edit' && ['list_of_clicks', 'list_of_products'].includes(temp.type))"
            >
              <el-form-item label="Text">
                <el-input v-model="temp.item.text" />
              </el-form-item>
              <!-- <el-form-item
                v-if="temp.style === 'picture' || temp.type === 'list_of_products'"
                label="Pict"
              >
                <image-upload />
              </el-form-item>-->
              <el-form-item label="Click">
                <el-input v-model="temp.item.click">
                  <template slot="prepend">
                    <div class="pic-prepend">
                      <el-select
                        v-model="temp.item.clickPrepend"
                        class="filter-item"
                        placeholder="Please select"
                      >
                        <el-option
                          v-for="item in clickTypes"
                          :key="item"
                          :label="item"
                          :value="item"
                        ></el-option>
                      </el-select>
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item v-if="temp.type === 'list_of_products'" label="Price">
                <el-input v-model="temp.item.price" />
              </el-form-item>
            </template>
          </template>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="closeDialog">Cancel</el-button>
        <el-button
          v-waves
          type="primary"
          @click="dialogStatus === 'add' ? addData() : editData()"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SubTableItem from "./SubTableItem.vue";
import NotIcon from './NotIcon.vue'
import waves from '@/directive/waves'
import ImageUpload from './ImageUpload.vue'
import Sortable from 'sortablejs'

export default {
  directives: { waves },
  components: { SubTableItem, 'not-icon': NotIcon, ImageUpload },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    rowKey: {
      type: String,
      default: ''
    },
    typeList: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update'],
  data() {
    return {
      tableKey: 0,
      list: [],
      temp: {
        type: '',
        text: '',
        mode: 'wrap',
        style: 'link',
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        click: '',
        clickPrepend: '',
        item: {
          text: '',
          price: '',
          click: '',
          clickPrepend: '',
          pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'
        }
      },
      clickTypes: ['http://', 'https://', 'activity://', 'open://'],
      loading: false,
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      sortable: null,
      expandRowKeys: []
    }
  },
  computed: {
    types() {
      return this.typeList
    }
  },
  mounted() {
    this.setSort()
  },
  methods: {
    onChangeType(val) {
      this.resetTemp();
      this.temp.type = val;
    },
    onExpandChange(row, expandedRows) {
      // this.expandRowKeys = expandedRows.map(item => item.items ? `${item.sid}` : '');
    },
    /* 重置 temp */
    resetTemp() {
      this.temp = {
        type: '',
        text: '',
        mode: 'wrap',
        style: 'link',
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        click: '',
        clickPrepend: '',
        item: {
          text: '',
          price: '',
          click: '',
          clickPrepend: '',
          pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'
        }
      }
    },
    /* 点击展开 */
    openDialogTable(index, sid) {
      // console.log(this.expandRowKeys, index)
      const idx = this.expandRowKeys.findIndex(item => item === sid)
      if (idx !== -1) {
        this.expandRowKeys.splice(idx, 1)
      } else {
        this.expandRowKeys.push(sid)
      }
    },
    /* 打开 弹窗 (创建) */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 添加 */
    addData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const item = this.formatData(this.temp)
          this.list.push({
            ...item,
            sid: `${Math.random().toString().slice(2)}_${Date.now()}`,
          })
          this.updateListItem()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Add Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /* 打开 弹窗 (更新)) */
    handleUpdate(row) {
      for (const k in row) {
        this.temp[k] = row[k] || ''
        if (this.clickTypes.some(item => this.temp['click'].includes(item))) {
          const arr = this.temp['click'].split('//');
          this.temp['clickPrepend'] = arr[0] + '//';
          this.temp['click'] = arr[1];
        }
      }
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 编辑 */
    editData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const { items, ...item } = this.formatData(this.temp)
          const index = this.list.findIndex(v => v.sid === this.temp.sid)
          // console.log(item, index, this.list[index])
          this.list.splice(index, 1, {
            ...this.list[index],
            ...item,
            sid: this.temp.sid
          })
          this.updateListItem()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /* 删除 */
    handleDelete(row, _index) {
      const index = this.list.findIndex(item => item.sid === row.sid)
      this.list.splice(index, 1)
      this.updateListItem();
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
    },
    closeDialog() {
      this.dialogFormVisible = false,
        this.resetTemp()
    },
    formatData(data) {
      let item = {};
      switch (data.type) {
        case 'title':
        case 'description':
          item = {
            type: data.type,
            text: data.text,
          }
          break;
        case 'one_big_picture':
          item = {
            type: data.type,
            pict: data.pict,
            click: data.clickPrepend + data.click,
          }
          break;
        case 'list_of_clicks':

          item = {
            type: data.type,
            style: data.style,
            mode: data.mode,
            items: [
              {
                text: data.item?.text,
                pict: data.style === 'picture' ? data.item?.pict : '',
                click: data.item?.clickPrepend + data.item?.click,
              }
            ]
          }
          break;
        case 'list_of_products':
          item = {
            type: data.type,
            mode: data.mode,
            items: [
              {
                price: data.item?.price,
                text: data.item?.text,
                pict: data.item?.pict,
                click: data.item?.clickPrepend + data.item?.click,
              }
            ]
          }
          break;
      }
      return item;
    },
    /* 行拖拽排序 */
    setSort() {
      const colDom = document.body.querySelectorAll('.expand-table-layout .el-table table colgroup');
      this.$nextTick(() => {
        Array.from(colDom).forEach(item => {
          // console.log(item.children[0])
          item.children[0].style.width = 0
        })
      })
      // colDom.children[0] && colDom.children[0].setAttribute('width', 0)
      const el = this.$refs.dragTable.$el.querySelectorAll('#expand-table-layout .el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        animation: 180,
        delay: 0,
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        draggable: '.el-table__row',
        setData: (dataTransfer) => {
          this.expandRowKeys = [];
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          // console.log(evt.oldIndex, evt.newIndex)
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          this.updateListItem();
        }
      })
    },
    updateListItem() {
      this.$nextTick(() => {
        this.$emit("update", {
          id: `${this.rowKey}`,
          newData: this.list
        })
      })
    },
    onUpdateList(data) {
      // console.log(data)
      const index = this.list.findIndex(item => item.sid === data.sid);
      if (index !== -1) {
        this.list[index] = data;
        this.updateListItem()
      }
    },
  },
  watch: {
    'data': {
      handler: function (val) {
        // console.log(val)
        this.list = JSON.parse(JSON.stringify(val))
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.items-layout {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background-color: #fff;
}

::v-deep .row-no-expand .el-table__expand-column .cell {
  pointer-events: none;
  display: none;
  width: 0;
}
/* row-no-expand .el-table__expand-column .el-icon{
  visibility:hidden;
} */

.pic-prepend {
  width: 100px;
}
</style>
